package com.wzs.rpc.protocol;

import com.wzs.rpc.serializer.Serializer;
import com.wzs.rpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class ProtocolMessageEncoder {
    public static Buffer encode(ProtocolMessage<?> protocolMessage) {
        Buffer buffer = Buffer.buffer();
        if (protocolMessage==null || protocolMessage.getHeader()==null) {
            return buffer;
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());

        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByValue(header.getSerializer());
        if (serializerEnum==null) {
            log.error("序列化器不存在");
            throw new RuntimeException("序列化器不存在");
        }
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getName());
        try {
            byte[] bytes = serializer.serialize(protocolMessage.getBody());
            buffer.appendInt(bytes.length);
            buffer.appendBytes(bytes);
            return buffer;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
